<template>
  <div class="dashboard-container">
    <el-alert
      v-show="false"
      title="警告提示的文案"
      type="warning"
      show-icon
      center
    />
    <div class="dashboard-text">
      <el-card class="box-card">
        <div slot="header" class="clearfix">
          <span>图书列表</span>
          <div class="input-with-div">
            <span>查询方式</span>
            <el-select slot="prepend" v-model="select1" class="mySelect1" placeholder="请选择" @change="change1($event)">
              <el-option label="无" value="null" />
              <el-option label="作者" value="book_author" />
              <el-option label="类别" value="book_type" />
              <el-option label="书名" value="book_name" />
              <el-option label="出版社" value="book_press" />
              <el-option label="状态" value="book_state" />
              <el-option label="库存" value="book_stock" />
            </el-select>
            <!-- <el-button slot="append">筛选</el-button> -->
            <el-row class="demo-autocomplete">
              <el-col :span="12" class="inline-col">
                <el-autocomplete
                  v-model="state1"
                  class="inline-input"
                  :fetch-suggestions="querySearch"
                  placeholder="请输入搜索内容"
                  @select="handleSelect"
                  @input="inputChange"
                />
                <el-button @click.enter="searchBook">查找</el-button>
              </el-col>
            </el-row>
            <span>所有类别</span>
            <el-select slot="prepend" v-model="select2" class="mySelect2" placeholder="请选择" @change="change2">
              <!-- <el-option label="网络类" value="1" />
              <el-option label="计算机类" value="2" />
              <el-option label="其他" value="3" /> -->
              <el-option value="全部" />
              <el-option v-for="(book,index) in bookType" :key="index" :value="book" />
            </el-select>
          </div>

        </div>
        <div>
          <template>
            <el-table
              :data="bookData"
              border
              style="width: 100%"
            >
              <el-table-column
                fixed
                prop="book_id"
                label="编号"
                width="120"
              />
              <el-table-column
                prop="book_author"
                label="作者"
                width="180"
              />
              <el-table-column
                prop="book_type"
                label="类别"
                width="100"
              />
              <el-table-column
                prop="book_name"
                label="书名"
                width="300"
              />
              <el-table-column
                prop="book_press"
                label="出版社"
                width="300"
              />
              <el-table-column
                prop="book_state"
                label="状态"
                width="100"
              />
              <el-table-column
                prop="book_stock"
                label="库存"
                width="80"
              />
              <el-table-column
                fixed="right"
                label="操作"
                width="160"
              >
                <template slot-scope="scope">
                  <el-button v-if="isUseBorrow(scope.row)" type="primary" size="small" @click="ifBorrowBook(scope.row)">借书</el-button>
                  <el-button v-else type="primary" size="small" @click="alterBorrow">借书中</el-button>
                  <el-button v-if="isUseOrder(scope.row)" size="small" @click="ifAppiont(scope.row)">预约</el-button>
                  <el-button v-else size="small" @click="alterOrder">预约中</el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
        </div>
        <div class="block">
          <el-pagination
            :current-page="value"
            :page-sizes="[10, 20, 30, 40]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>

import { getBookinfo, boBook } from '@/api/book'
import { borUse, getUserInfo } from '@/api/user'
import { formatDate, AfterDate } from '@/utils/auth'
export default {
  name: 'Dashboard',
  data() {
    return {
      select1: '',
      select2: '全部',
      restaurants: [],
      state1: '',
      bookData: [],
      searchType: 'book_name',
      bookType: [],
      total: 0,
      value: 1,
      offset: 10,
      userinfo: {
        user_name: '',
        book_name: '',
        borrowOrOderTime: '',
        isBorrow: false,
        isOrder: false,
        book_id: '',
        returnTime: ''
      },
      AllBook: [],
      isFilter: false,
      bookFilterData: [],
      borOrOrder: []
    }
  },
  computed: {

  },
  async created() {
    const arr = []
    const bookData = await getBookinfo()
    const { data } = await getUserInfo({ user_name: localStorage.getItem('user_name') })
    this.borOrOrder = data
    // console.log(data)
    this.total = bookData.total
    this.bookData = [...bookData.data]
    this.AllBook = bookData.totalData
    bookData.totalData.forEach(item => {
      arr.push(item.book_type)
    })
    this.bookType = [...new Set(arr)]
    console.log('bookData', this.bookData)
  },
  methods: {
    querySearch(queryString, cb) {
      var restaurants = this.restaurants
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect(item) {
      console.log(item)
    },
    // 每行页数改变的时候触发的函数
    async handleSizeChange(val) {
      // console.log('handleSizeChange')
      this.offset = val
      const bookData = await getBookinfo(this.value, val)
      this.bookData = [...bookData.data]
    },
    // 当每行页数发送改变时候触发的最多页数的改变
    async handleCurrentChange(val) {
      // console.log('handleSizeChange')
      this.value = val
      // console.log(this.bookFilterData, this.value)
      if (this.isFilter) {
        this.filterBook()
      } else {
        this.renderBook(this.value, this.offset)
      }
      // const bookData = await getBookinfo(val, this.offset)
      // this.bookData = [...bookData.data]
    },
    change1(e) {
      if (e === 'null') {
        this.renderBook(this.value, this.offset)
      } else {
        this.searchType = e
      }
    },
    searchBook() {
      const that = this
      this.bookData = this.AllBook.filter(item => item[that.searchType] === that.state1)
    },
    // 当搜索框的内容为空的时候，重新渲染图书列表
    async inputChange() {
      if (this.state1 === '') {
        this.renderBook(this.value, this.offset)
      }
    },
    // 筛选图书的处理函数
    async change2() {
      const bookData = await getBookinfo(this.value, this.offset)
      this.bookData = [...bookData.data]
      this.value = 1
      // this.renderBook(this.value, this.offset)
      if (this.select2 === '全部') {
        this.isFilter = false
        this.renderBook(this.value, this.offset)
        this.total = this.AllBook.length
        return
      } else {
        this.filterBook()
        this.total = this.bookFilterData.length
        this.isFilter = true
      }
    },
    // 借书的处理函数
    ifBorrowBook(bookinfo) {
      console.log('bookinfo=>', bookinfo)
      const user_name = localStorage.getItem('user_name')
      const arr = JSON.parse(bookinfo.if_book_borrowUse).filter(item => item.user === user_name)[0] || []
      // console.log(arr)
      if (!bookinfo.book_stock) {
        return this.$notify.error({
          title: '错误',
          message: '库存不足,无法借书!'
        })
      } else if (arr.isOrder) {
        return this.$message.error('已预约过此书，无法借阅!')
      } else {
        this.$confirm('该图书可以进行借阅, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(async() => {
          // console.log(formatDate(new Date()))
          this.userinfo.user_name = localStorage.getItem('user_name')
          this.userinfo.book_name = bookinfo.book_name
          this.userinfo.borrowOrOderTime = formatDate(new Date())
          this.userinfo.returnTime = AfterDate(new Date())
          this.userinfo.book_id = bookinfo.book_id
          this.userinfo.isBorrow = true
          this.userinfo.isOrder = false
          await boBook(this.userinfo)
          await borUse(this.userinfo)
          this.renderBook()
          this.$message({
            type: 'success',
            message: '借书成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      }
    },
    // 预约图书的处理函数
    ifAppiont(bookinfo) {
      const user_name = localStorage.getItem('user_name')
      const arr = JSON.parse(bookinfo.if_book_borrowUse).filter(item => item.user === user_name)[0] || []
      if (bookinfo.book_state === '预约') {
        this.$notify.error({
          title: '错误',
          message: '该图书已经被预约,请稍等几日后再预约!'
        })
      } else if (arr.isBorrow) {
        this.$message.error('已借阅过此书，无法再次预约!')
      } else {
        this.$confirm('该图书可以进行预约, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(async() => {
          this.userinfo.user_name = localStorage.getItem('user_name')
          this.userinfo.book_name = bookinfo.book_name
          this.userinfo.borrowOrOderTime = formatDate(new Date())
          this.userinfo.returnTime = ''
          this.userinfo.book_id = bookinfo.book_id
          this.userinfo.isOrder = true
          this.userinfo.isBorrow = false
          await boBook(this.userinfo)
          await borUse(this.userinfo)
          this.renderBook()
          this.$message({
            type: 'success',
            message: '预约成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消预约'
          })
        })
      }
    },
    // 初始化bookinfo
    async renderBook(book1, book2) {
      const bookData = await getBookinfo(book1, book2)
      this.bookData = [...bookData.data]
    },
    filterBook() {
      this.bookFilterData = [...this.AllBook.filter(item => item.book_type === this.select2)]
      this.bookData = this.bookFilterData.filter((item, index) => {
        if ((1 + (this.value - 1) * this.offset) - 1 <= index && index < (this.value * this.offset) - 1) {
          return item
        }
      })
    },
    isUseBorrow(info) {
      const user_name = localStorage.getItem('user_name')
      const falg = JSON.parse(info.if_book_borrowUse).filter(item => item.user === user_name)[0] || []
      // console.log('falg', falg[0].isBorrow)
      return !falg.isBorrow || false
    },
    isUseOrder(info) {
      const user_name = localStorage.getItem('user_name')
      const falg = JSON.parse(info.if_book_borrowUse).filter(item => item.user === user_name)[0] || []
      // console.log('falg', falg[0].isBorrow)
      return !falg.isOrder || false
    },
    alterBorrow() {
      this.$message.error('已借过此书，无法再次借阅!')
    },
    alterOrder() {
      this.$message.error('已预约过此书，无法再次预约!')
    }

  }

}
</script>

<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
 .text {
    font-size: 14px;
  }

  .item {
    margin-bottom: 18px;
  }

  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both
  }

  .box-card {
    // width: 480px;
    font-size: 24px;
  }
  .el-select .el-input {
    width: 130px;
  }
  .input-with-div{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    // width: 500px;
    font-size: 14px;
    span{
      margin: 0 10px;
    }
    .inline-col {
      display: flex;
      width: 300px;
      margin: 0 20px;
    }
  }
  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .mySelect1{
    width: 100px;
    text-align: center;
    padding: 0;
  }
   .mySelect2{
     margin:0px;
    width: 100px;
    text-align: center;
    padding: 0;
  }
  .inline-input{
    margin-right: 10px;
  }
  .block {
    margin-top: 30px;
  }
</style>
